﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using log4net;


namespace BidFunLib.DAO
{
    /// <summary>
    /// This class manage Hibernate session creation
    /// </summary>
    public sealed class NHibernateHelper
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(NHibernateHelper));



        /// <summary>
        /// 
        /// </summary>
        private static ISessionFactory sessionFactory;

        /// <summary>
        /// Open a database session to access the database
        /// At first call it instantiate the hiberante sessionFactory
        /// </summary>
        /// <returns></returns>
        public static ISession OpenSession()
        {
            if (sessionFactory == null)
            {
                log.Debug("Session factory creation...");
                Configuration c = new Configuration();
                Console.WriteLine("Fin configuration...");

                c.Configure("App.config");

                sessionFactory = c.BuildSessionFactory();
                log.Debug("Session factory created sucessfully !");
            }
            return sessionFactory.OpenSession();
        }


        /// <summary>
        /// Close the session factory to end properly the program
        /// </summary>
        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                log.Debug("Closing Session factory");
                sessionFactory.Close();
            }
        }
    }
}
